const express = require('express')
const router = express.Router()
const Subscriber = require('../models/subscriber')

// 列表
router.get('/', async(req, res)=>{
  try {
    const subscribers = await Subscriber.find().populate('category_id', 'id title')
    res.json({
      code: 200,
      data: subscribers,
      msg: 'ok'
    })
  } catch (error) {
    res.status(500).json({ msg: error.message })
  }
})

// 详情
router.get('/:id',getSubscriber, async(req, res)=>{
  res.json({
    code: 200,
    data: res.subscriber,
    msg: '获取成功'
  })
})

// 创建
router.post('/', async(req, res) => {
  const subscriber = new Subscriber({
    name: req.body.name,
    category_id: req.body.category_id,
    subscribedChannel: req.body.subscribedChannel
  })
  try {
    const newSubscriber = await subscriber.save()
    res.status(201).json({
      code: 200,
      data: newSubscriber,
      msg: '新增成功'
    })
  } catch (error) {
    res.status(500).json({ msg: error.message })
  }
})

// 更新
router.patch('/:id',getSubscriber, async(req, res) => {
  // 选择新更新
  if (req.body.name != null) {
    res.subscriber.name = req.body.name
  }

  if (req.body.subscribedChannel != null) {
    res.subscriber.subscribedChannel = req.body.subscribedChannel
  }

  try {
    const updatedSubscriber = await res.subscriber.save()
    res.json({
      code: 200,
      data: updatedSubscriber,
      msg: '更新成功'
    })
  } catch (error) {
    res.status(400).json({ msg: error.message })
  }
})

// 删除
router.delete('/:id',getSubscriber, async(req, res) => {
  try {
    await res.subscriber.remove()
    res.json({
      code: 200,
      msg: '删除成功'
    })
  } catch (error) {
    res.status(500).json({ msg: error.message })
  }
})


// 定义中间件
// 通过id获取某一项
async function getSubscriber(req, res, next) {
  try {
    subscriber = await Subscriber.findById(req.params.id).populate('category_id', 'id title')
    if (subscriber == null) {
      return res.status(404).json({ message: 'Cant find subscriber'})
    }
  } catch(err){
    return res.status(500).json({ message: err.message })
  }

  res.subscriber = subscriber
  next()
}

module.exports = router